/**
 * Copyright (C) 2003-2008 xuesong.net
 * http://www.xuesong.net
 * Author: xuesong.net
 **/
var Rabbit = {};

Rabbit.getVariable = function(name) {
    if(typeof(window.localStorage) != "undefined") {
        return window.localStorage[name];
    }
    else {
        return CookieUtil.getCookie(name);
    }
};

Rabbit.setVariable = function(name, value) {
    if(typeof(window.localStorage) != "undefined") {
        window.localStorage[name] = value;
    }
    else {
        CookieUtil.setCookie({"name": name, "value": value, "expires": 7 * 24 * 60 * 60});
    }
};

var Footprint = {};

Footprint.setValue = function() {
    var a = ["0"];
    var args = arguments;

    for(var i = 0; i < args.length; i++) {
        a[a.length] = args[i];
    }
    Rabbit.setVariable("footprint", a.join("_"));
};

Footprint.getValue= function() {
    var userId = "0";
    var value = Rabbit.getVariable("footprint");

    if(value != null) {
        var a = value.split("_");

        if(a.length >= 2 && a[0] == userId) {
            return a[1];
        }
    }
    return null;
};

Footprint.getBookmark = function(archiveId) {
    var userId = "0";
    var value = Rabbit.getVariable("footprint");

    if(value != null) {
        var a = value.split("_");

        if(a.length >= 2 && a[0] == userId) {
            if(archiveId != null && archiveId != a[1]) {
                return;
            }

            var bookmark = {"id": a[1], "top": 0};

            if(a.length >= 3) {
                bookmark.top = a[2];
            }
            return bookmark;
        }
    }
    return null;
};

var TableUtil = {};

TableUtil.prev = function(tr) {
    var e = tr.previousSibling;

    while(true) {
        if(e == null) {
            return null;
        }
        else if(e.nodeType == 1) {
            return e;
        }
        else {
            e = e.previousSibling;
        }
    }
};

TableUtil.next = function(tr) {
    var e = tr.nextSibling;

    while(true) {
        if(e == null) {
            return null;
        }
        else if(e.nodeType == 1) {
            return e;
        }
        else {
            e = e.nextSibling;
        }
    }
};

TableUtil.moveup = function(tr) {
    var prev = this.prev(tr);

    if(prev != null) {
        this.swap(prev, tr);
    }
};

TableUtil.movedown = function(tr) {
    var next = this.next(tr);

    if(next != null) {
        this.swap(tr, next);
    }
};

TableUtil.swap = function(r1, r2) {
    if(r1 == null || r2 == null) {
        return false;
    }

    var n1 = r1.rowIndex;
    var n2 = r2.rowIndex;

    if(n1 == n2) {
        return false;
    }

    if(n1 > n2) {
        return this.swap(r2, r1);
    }

    var r3 = r2.nextSibling;
    var parent = r1.parentNode;

    parent.removeChild(r2);
    parent.insertBefore(r2, r1);

    if(Math.abs(n1 - n2) > 1) {
        if(r3 != null) {
            parent.removeChild(r1);
            parent.insertBefore(r1, r3);
        }
        else {
            parent.removeChild(r1);
            parent.appendChild(r1);
        }
    }
};

var ImageUtil = {};

ImageUtil.resize = function(img, maxWidth, maxHeight) {
    if(img.readyState != "complete") {
    }

    img.style.width = "auto";
    img.style.height = "auto";
    var widthHeight = (img.offsetWidth / img.offsetHeight);
    var heightWidth = (img.offsetHeight / img.offsetWidth);

    var realWidth = maxWidth
    var realHeight = Math.floor(maxWidth / widthHeight);

    if(realHeight > maxHeight) {
        realHeight = maxHeight;
        realWidth = Math.floor(maxHeight / heightWidth);
    }

    if(img.offsetWidth < maxWidth && img.offsetHeight < maxHeight) {
        realWidth = img.offsetWidth
        realHeight = img.offsetHeight;
    }

    if(img.parentNode.className == "img-float") {
        img.parentNode.style.width = (realWidth + 20) + "px";
        img.parentNode.style.height = realHeight + "px";
    }

    img.style.width = realWidth + "px";
    img.style.height = realHeight + "px";
};

var FavoriteManager = {};

FavoriteManager.setFavorites = function(favorites) {
    this.favorites = favorites;
    this.version = new Date().getTime().toString();
    Rabbit.setVariable("favoritesVersion", this.version);
};

FavoriteManager.getFavorites = function(error, success) {
    if(this.favorites != null) {
        var version = Rabbit.getVariable("favoritesVersion");

        if(version == this.version) {
            if(success != null) {
                success(this.favorites);
            }
            return;
        }
    }

    jQuery.ajax({
        "type": "get",
        "url": PageContext.getContextPath() + "/note/favorite/getFavorites.html",
        "dataType": "json",
        "error": error,
        "success": function(result) {
            FavoriteManager.setFavorites(result.value);

            if(success != null) {
                success(result.value);
            }
        }
    });
};

FavoriteManager.add = function(archiveId, callback) {
    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/favorite/collect.html",
        "data": "archiveId=" + archiveId,
        "dataType": "json",
        "error": function() {
            console.log("collect failed.");
        },
        "success": function(result) {
            FavoriteManager.setFavorites(null);

            if(callback != null) {
                callback(result);
            }
        }
    });
};

FavoriteManager.cancel = function(archiveId, callback) {
    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/favorite/cancel.html",
        "data": "archiveId=" + archiveId,
        "dataType": "json",
        "error": function() {
            console.log("collect failed.");
        },
        "success": function(result) {
            FavoriteManager.setFavorites(null);

            if(callback != null) {
                callback(result);
            }
        }
    });
};

jQuery(function() {
    /**
     * 下拉框显示默认值
     **/
    jQuery("select").each(function() {
        var selectedValue = this.getAttribute("selected-value");

        if(selectedValue != null && selectedValue != "") {
            var options = this.options;

            for(var i = 0; i < options.length; i++) {
                if(options[i].value == selectedValue) {
                    this.value = selectedValue;
                    break;
                }
            }
        }
    });

    /**
     * 复选框显示选中状态
     **/
    jQuery("input[type=checkbox][dataType=boolean]").each(function() {
        if(this.value == "1") {
            this.checked = true;
        }

        jQuery(this).click(function() {
            if(this.checked == true) {
                this.value = 1;
            }
            else {
                this.value = 0;
            }
        });
    });

    /**
     * 货币类型
     **/
    jQuery("input[type=text][dataType=currency]").change(function() {
        var value = this.value;

        if(isNaN(value)) {
            this.value = "0.00";
            return true;
        }
        this.value = parseFloat(value, 10).toFixed(2);
        return true;
    });

    jQuery("span[dataType=currency]").change(function() {
        var value = this.innerHTML;

        if(isNaN(value)) {
            jQuery(this).html("0.00");
            return true;
        }
        jQuery(this).html(parseFloat(value, 10).toFixed(2));
        return true;
    });

    /**
     * 单精度类型
     **/
    jQuery("input[type=text][dataType=float]").change(function() {
        var value = this.value;
        var precision = this.getAttribute("precision");

        if(precision == null || isNaN(precision)) {
            precision = 2;
        }

        if(precision < 0) {
            precision = 0;
        }

        if(isNaN(value)) {
            this.value = (0).toFixed(precision);
            return true;
        }
        this.value = parseFloat(value, 10).toFixed(precision);
        return true;
    });

    jQuery("span[dataType=float]").change(function() {
        var value = this.innerHTML;
        var precision = this.getAttribute("precision");

        if(precision == null || isNaN(precision)) {
            precision = 2;
        }

        if(precision < 0) {
            precision = 0;
        }

        if(isNaN(value)) {
            jQuery(this).html((0).toFixed(precision));
            return true;
        }
        jQuery(this).html(parseFloat(value, 10).toFixed(precision));
        return true;
    });

    jQuery("span.dictionary").each(function() {
        var key = jQuery(this).attr("key");
        var e = document.getElementById(jQuery(this).attr("refId"));

        if(e != null) {
            var options = e.options;

            for(var i = 0; i < options.length; i++) {
                var option = options[i];

                if(key == option.value) {
                    jQuery(this).html(option.text);
                    return;
                }
            }
        }
        jQuery(this).html("未知");
    });

    jQuery("input[type=text][dataType=currency]").change();
    jQuery("input[type=text][dataType=float]").change();

    jQuery("span[dataType=currency]").change();
    jQuery("span[dataType=float]").change();
});

jQuery(function() {
    jQuery("div.content img").bind("load", function() {
        var width = 740;
        var height = Math.floor(width * 0.618);
        ImageUtil.resize(this, width, height);
        jQuery(this).show();
    });

    jQuery("div.img-float").each(function() {
        var src = jQuery(this).attr("src");

        if(src != null) {
            jQuery(this).html("<img src=\"about:blank\"/>");

            jQuery(this).find("img").load(function() {
                ImageUtil.resize(this, 268, 433);
            });
            jQuery(this).find("img").attr("src", src);
        }
    });

    jQuery("a.wiki-list").click(function() {
        var itemId = jQuery(this).attr("itemId");

        if(itemId != null) {
            jQuery(this).attr("href", PageContext.getContextPath() + "/note/archive/list.html?itemId=" + itemId);
        }
    });

    jQuery("a.wiki-create").each(function() {
        var itemId = jQuery(this).attr("itemId");

        if(itemId != null) {
            jQuery(this).attr("href", PageContext.getContextPath() + "/note/archive/create.html?itemId=" + itemId);
        }
    });

    jQuery("#wiki-edit-menu li").click(function() {
        var archiveId = jQuery(this).attr("archiveId");
        var mimeType = jQuery(this).attr("mimeType");
        window.location.href = PageContext.getContextPath() + "/note/archive/edit.html?archiveId=" + archiveId + "&mimeType=" + encodeURIComponent(mimeType);
    });
});

/**
 * 编辑模式 - markdown支持
 */
jQuery(function() {
    if(typeof(marked) == "undefined") {
        return;
    }

    jQuery("textarea.markdown").each(function() {
        var parent = this.parentNode;
        var c = document.createElement("div");
        c.innerHTML = marked(this.value, {breaks: true});

        if(this.nextSibling != null) {
            parent.insertBefore(c, this.nextSibling);
        }
        else {
            parent.appendChild(c);
        }
    });
});

/**
 * 只读模式 - 高亮
 */
jQuery(function() {
    if(typeof(hljs) == "undefined") {
        return;
    }

    jQuery("div.wiki-content pre").each(function() {
        if(this.innerText != null) {
            var txt = this.innerText;

            /**
             * 1. 删除行尾空格
             * 2. 清除多余换行
             */
            txt = txt.replace(/ /g, " ");
            txt = txt.replace(/[ ]*\n/g, "\n");
            txt = txt.replace(/&nbsp;/g, " ");
            txt = txt.replace(/<br\/>/g, "\n");

            this.innerHTML = "";
            this.appendChild(document.createTextNode(txt));
        }
        hljs.highlightBlock(this);
    });
});

/**
 * do nothing
 */
jQuery(function() {
    jQuery("#notexists").click(function() {
        window.location.reload();
    });
});

/**
 *
 */
jQuery(function() {
    jQuery("#refresh-btn").click(function() {
        window.location.reload();
    });
});

/**
 * 编辑页面
 */
jQuery(function() {
    var owner = PageContext.getAttribute("owner");
    var password = PageContext.getAttribute("password");

    if(owner != "true") {
        jQuery("#setting-btn div.menu").remove();
        return;
    }

    jQuery("#setting-btn").removeClass("disabled");
    jQuery("#setting-btn").click(function() {
        jQuery(this).find("div.menu").show();
    });

    /**
     * 阅读密码
     */
    if(password == "******") {
        jQuery("#secret-btn").html("取消阅读密码");
        jQuery("#pass-panel button.create-password").remove();
        jQuery("#pass-panel input[name=password1]").val("******").prop("disabled", true);
        jQuery("#pass-panel input[name=password2]").closest("div.form-r64").remove();
    }
    else {
        jQuery("#secret-btn").html("设置阅读密码");
        jQuery("#pass-panel button.remove-password").remove();
    }

    jQuery("#secret-btn").click(function() {
        jQuery("#pass-panel").css("width", document.documentElement.clientWidth);
        jQuery("#pass-panel").show();
    });

    jQuery("#pass-panel").find("button.cancel").click(function() {
        jQuery("#pass-panel").hide();
    });

    var invoke = function(callback) {
        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/token/getCSRFToken.html",
            "dataType": "json",
            "error": function() {
                alert("系统错误，请稍后再试。");
            },
            "success": function(result) {
                callback(result.value);
            }
        });
    };

    /**
     * 取消阅读密码
     */
    jQuery("#pass-panel").find("button.remove-password").click(function() {
        invoke(function(token) {
            var params = {};
            params.archiveId = PageContext.getLong("archiveId");
            params._csrf_token = token;

            jQuery.ajax({
                "type": "post",
                "url": PageContext.getContextPath() + "/note/archive/password/cancel.html",
                "data": jQuery.param(params, true),
                "dataType": "json",
                "error": function() {
                    alert("系统错误，请稍后再试。");
                },
                "success": function(result) {
                    window.location.reload();
                }
            });
        });
    });

    /**
     * 设置阅读密码
     */
    jQuery("#pass-panel").find("button.create-password").click(function() {
        var archiveId = PageContext.getLong("archiveId");
        var password1 = jQuery.trim(jQuery("#pass-panel").find("input[name=password1]").val());
        var password2 = jQuery.trim(jQuery("#pass-panel").find("input[name=password2]").val());

        if(password1 == "******") {
            alert("无效的密码。");
            return;
        }

        if(password1 != password2) {
            alert("两次密码不匹配.");
            return;
        }

        var getSalt = function(length) {
            var buffer = [];
            var chars = "0123456789abcdef";

            for(var i = 0; i < length; i++) {
                buffer[i] = chars[Math.floor(Math.random() * chars.length)];
            }
            return buffer.join("");
        };

        var salt = getSalt(6);
        var digest = sha1.create();
        digest.update(salt);
        digest.update(password1);

        invoke(function(token) {
            var params = {};
            params.archiveId = archiveId;
            params.salt = salt;
            params.password = digest.toString();
            params._csrf_token = token;

            jQuery.ajax({
                "type": "post",
                "url": PageContext.getContextPath() + "/note/archive/setPassword.html",
                "data": jQuery.param(params, true),
                "dataType": "json",
                "error": function() {
                    alert("系统错误，请稍后再试。");
                },
                "success": function(result) {
                    window.location.reload();
                }
            });
        });
    });

    /**
     * 文档属性
     */
    jQuery("#props-btn").click(function() {
        jQuery("#prop-panel").css("width", document.documentElement.clientWidth);
        jQuery("#prop-panel").show();
    });

    jQuery("#prop-panel").find("button.cancel").click(function() {
        jQuery("#prop-panel").hide();
    });

    jQuery("#prop-panel").find("button.ensure").click(function() {
        var archiveId = PageContext.getLong("archiveId");
        var mimeType = jQuery("#prop-panel").find("select[name=mimeType]").val();
        var theme = jQuery("#prop-panel").find("select[name=theme]").val();
        var params = {};
        params.archiveId = archiveId;
        params.mimeType = mimeType;
        params.theme = theme;

        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/archive/setProperties.html",
            "data": jQuery.param(params, true),
            "dataType": "json",
            "error": function() {
                alert("系统错误，请稍后再试。");
            },
            "success": function(result) {
                window.location.reload();
            }
        });
    });

    /**
     * 分享文档
     */
    jQuery("#share-btn").click(function() {
        jQuery("#share-panel").css("width", document.documentElement.clientWidth);
        jQuery("#share-panel").show();

        /**
         * 加载token
         */
        var archiveId = PageContext.getLong("archiveId");

        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/archive/getToken.html",
            "data": "archiveId=" + archiveId,
            "dataType": "json",
            "error": function() {
                jQuery("#share-link").html("<span class=\"red\">系统错误，请稍后再试。</span>");
            },
            "success": function(result) {
                Response.success(result, function(value) {
                    if(value == null) {
                        jQuery("#share-link").html("您尚未设置分享链接。");
                    }
                    else {
                        jQuery("#share-link").html(PageContext.getURL("/note/archive/display.html?key=" + value));
                    }
                });
            }
        });
    });

    jQuery("#share-panel").find("button.cancel").click(function() {
        jQuery("#share-panel").hide();
    });

    jQuery("#share-panel").find("button.generate").click(function() {
        var archiveId = PageContext.getLong("archiveId");

        jQuery.ajax({
            "type": "post",
            "url": PageContext.getContextPath() + "/note/archive/token/generate.html",
            "data": "archiveId=" + archiveId,
            "dataType": "json",
            "error": function() {
                jQuery("#share-link").html("<span class=\"red\">系统错误，请稍后再试。</span>");
            },
            "success": function(result) {
                Response.success(result, function(value) {
                    jQuery("#share-link").html(PageContext.getURL("/note/archive/display.html?key=" + value));
                });
            }
        });
    });
});

jQuery(function() {
    if(jQuery("#favorite-btn").size() < 1) {
        return;
    }

    var favorite = jQuery("#favorite-btn").attr("favorite");

    if(favorite == "true") {
        jQuery("#favorite-btn").html("取消收藏");
    }
    else {
        jQuery("#favorite-btn").html("收藏");
    }

    jQuery("#favorite-btn").click(function() {
        var src = jQuery(this);
        var favorite = src.attr("favorite");
        var archiveId = PageContext.getAttribute("archiveId");

        if(favorite != "true") {
            FavoriteManager.add(archiveId, function() {
                src.html("取消收藏");
                src.attr("favorite", "true");
            });
        }
        else {
            FavoriteManager.cancel(archiveId, function() {
                src.html("收藏");
                src.attr("favorite", "false");
            });
        }
    });
});

jQuery(function() {
    if(jQuery("#favorite-ico").size() < 1) {
        return;
    }

    var favorite = jQuery("#favorite-ico").attr("favorite");

    if(favorite == "true") {
        jQuery("#favorite-ico").attr("title", "取消收藏");
        jQuery("#favorite-ico").attr("class", "favorite1");
    }
    else {
        jQuery("#favorite-ico").attr("title", "添加收藏");
        jQuery("#favorite-ico").attr("class", "favorite2");
    }

    jQuery("#favorite-ico").click(function() {
        var src = jQuery(this);
        var favorite = src.attr("favorite");
        var archiveId = PageContext.getAttribute("archiveId");

        if(favorite != "true") {
            FavoriteManager.add(archiveId, function() {
                src.attr("class", "favorite1");
                src.attr("favorite", "true");
                src.attr("title", "取消收藏");
            });
        }
        else {
            FavoriteManager.cancel(archiveId, function() {
                src.attr("class", "favorite2");
                src.attr("favorite", "false");
                src.attr("title", "添加收藏");
            });
        }
    });
});

/**
 * footprint
 */
jQuery(function() {
    var userId = 0;
    var archiveId = PageContext.getLong("archiveId");

    if(archiveId < 1) {
        return;
    }

    var value = Footprint.getValue();

    if(archiveId == value) {
        return;
    }

    Footprint.setValue(archiveId);
    jQuery.ajax({"type": "get", "url": PageContext.getContextPath() + "/note/footprint/touch.html?archiveId=" + archiveId});
});

